/*
 * Copyright (c) 2005-2006 Rincon Research Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the
 *   distribution.
 * - Neither the name of the Rincon Research Corporation nor the names of
 *   its contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * RINCON RESEARCH OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE
 */
 
#include "Timer.h"
#include "RssiToSerial.h"
#include "printf.h"
 
 /**
  * This is more of a general demonstration than a test.
  *
  * Install this application to one node, connected to the computer.
  * The node will measure the environmental RSSI from the CC2420 and
  * sending those readings over the serial port.
  *
  * Use the Java application to display the relative RSSI readings.
  *
  * @author Jared Hill
 * @date   23 March 2007
  */
 
module RssiToSerialP {
  uses {
    interface Leds;
    interface Boot;
    interface AMSend;
    interface SplitControl as AMControl;
    interface SplitControl as SerialControl;
    interface Packet;
    interface Read<uint16_t> as ReadRssi;
    interface CC2420Config as Config;

	interface State as WorkingState;
	interface SpiByte;
	interface Timer<TMilli> as SerialTimer;
	interface GeneralIO as CSN;
  }
}
implementation {

 enum {
       S_IDLE,
       S_BUSY,
     };


  /******* Global Variables ****************/
  message_t packet;
  bool locked;
  uint32_t total;
  uint16_t largest;
  uint16_t reads;

	uint8_t samples[6000];
	uint16_t sampleNum = 0;
	uint16_t packetNum = 0;
	uint16_t index = 0;
	uint16_t NoSample = 0;

	bool sampleFlag = TRUE;
  
  /******** Declare Tasks *******************/
  task void readRssi();
  task void sendSerialMsg();
  
  /************ Boot Events *****************/
  event void Boot.booted() {
    call AMControl.start();
    total = 0;
    largest = 0;
    reads = 0;
    locked = FALSE;
  }

  /************ AMControl Events ******************/
  event void AMControl.startDone(error_t err) {
    if (err == SUCCESS) {
      call SerialControl.start();
    }
    else {
      call AMControl.start();
    }
  }

  event void AMControl.stopDone(error_t err) {
    // do nothing
  }

	void initiation() {
		int i =0;
		for(;i<6000;i++) {
			samples[i] = 0;
		}	
	}


	/*********** Request reading RSSI ****************/
	error_t request() {

	atomic {
		
	       if ( call WorkingState.requestState(S_BUSY) == SUCCESS ) {
	     		return SUCCESS;
	       } else { 
	       		request();
	       }
	     }
	     return SUCCESS;

	}

	error_t release() {
		atomic {
			call CSN.set();
			call WorkingState.toIdle();
			return SUCCESS;
		}
	}

	/********* Read RSSI Register Directly**********/
	cc2420_status_t  RSSIRead(uint16_t* data) {
	atomic {
		cc2420_status_t status = 0;
/*
		if(request()!=SUCCESS) {
			RSSIRead(data);
		}
*/
		call CSN.clr();
		call CSN.clr();
		
	 /*
		     atomic {
		       if(call WorkingState.isIdle()) {
		        return status;
		       }
		     }
	*/
		status = call SpiByte.write(0x13 | 0x40);
		*data = (uint16_t) call SpiByte.write(0)<<8;
		*data |= call SpiByte.write(0);

		call CSN.set();
		return status;
	}
	}
  

  /***************SerialControl Events*****************/
  event void SerialControl.startDone(error_t error){
  	int i = 0;
	uint16_t data = 0;
    if (error == SUCCESS) {
	initiation();
	for(i=0;i<3000;i++) {

		RSSIRead(&data);
//if(i>1){call Leds.led1Toggle();}
		//release();
		samples[i] = data;
		
	}
	call SerialTimer.startOneShot(5000);
      //post readRssi();
    }
    else {
      call AMControl.start();
    }
  }
  
  event void SerialControl.stopDone(error_t error){
    //do nothing
  }
  
  /***************** AMSend Events ****************************/
  event void AMSend.sendDone(message_t* bufPtr, error_t error) {
    
    call Leds.led2Toggle();
    if (&packet == bufPtr) {
      locked = FALSE;
      	//call Leds.led1Off();
    
	index++;
	if(index<packetNum){
		post sendSerialMsg();
	}
    }
    //post readRssi();
  }




  
  /**************** ReadRssi Events *************************/
  event void ReadRssi.readDone(error_t result, uint16_t val ){

	uint8_t temp;
    
    if(result != SUCCESS){
      post readRssi();
      return;
    }
    atomic{
	temp = (uint8_t)(val);
	samples[reads++] = temp;
/*
	temp = val;
	temp -= 127;
	if(temp>=127) {
		temp = temp - 256 - 45;
	}
	else {
		temp = temp - 45;
	}
	val = temp;
	total += temp;
	reads++;
	if(largest < temp){
		largest = temp;
     	}
*/
    } 
    //if(reads == (1<<LOG2SAMPLES)){
    //if(reads == 2){
    //  post sendSerialMsg();
    //}
    if(sampleFlag){
    	post readRssi();
    }
    
  }

	event void SerialTimer.fired() {
		sampleFlag = FALSE;
		sampleNum = reads;
		packetNum = (sampleNum/2) +1;
			//samples[0] = sampleNum;
			//samples[1] = packetNum;
	//waiting last packet sendout
	//while(locked){ call Leds.led1On();}
		post sendSerialMsg();
	}
  
  /********************* Config Events *************************/
  event void Config.syncDone(error_t error){
  
  }

  /***************** TASKS *****************************/  
  task void readRssi(){
   
    if(call ReadRssi.read() != SUCCESS){
      post readRssi();
    }
  }
  
  task void sendSerialMsg(){
/*
	if(NoSample>200) {call Leds.led1On();}
    if(index>=packetNum){
	call Leds.led0On();
    	return;
    }
    if(locked){
      return;
    }
    else {
      rssi_serial_msg_t* rsm = (rssi_serial_msg_t*)call Packet.getPayload(&packet, sizeof(rssi_serial_msg_t));
      
      if (call Packet.maxPayloadLength() < sizeof(rssi_serial_msg_t)) {
	    return;
      }
	  atomic{
	    //rsm->rssiAvgValue = (total >> (LOG2SAMPLES));
	    //rsm->rssiLargestValue = largest;
	  }
		rsm->rssiAvgValue = samples[NoSample++];
		rsm->rssiLargestValue = samples[NoSample++];
	      rsm->channel = call Config.getChannel();
	      if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(rssi_serial_msg_t)) == SUCCESS) {
		    locked = TRUE;
	      }

    }
  
*/
	call Leds.led0On();
	printf ("%u\n", sampleNum);
	for(NoSample = 0;NoSample<sampleNum;) {
		//printf("%u \t %u\n", NoSample, samples[NoSample++]);
		printf("%u\n", samples[NoSample++]);
		
	}

	printfflush();
	call Leds.led2On();
   }
 }




